package solutions.ferpa.ztest.intf;

import br.com.telescope.adsrt.dom.DomBigInteger;
import br.com.telescope.adsrt.dom.DomId;
import br.com.telescope.adsrt.dom.DomInteger;
import br.com.telescope.adsrt.dom.DomPasswordHash;
import br.com.telescope.adsrt.dom.DomTextLong;
import br.com.telescope.adsrt.dom.DomUpper;
import br.com.telescope.adsrt.lib.*;
import br.com.telescope.adsrt.lib.Field;
import br.com.telescope.sequence.SequenceManager;
import br.com.telescope.t2.AccessPolicy;
import br.com.telescope.t2.ServiceModel;
import br.com.telescope.t2.exception.ApplicationRuntimeException;
import br.com.telescope.t2.feature.CustomActionFeature;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import solutions.ferpa.ztest.ent.*;

/**
 * Serviço de replicação de sequencias.
 * <p>
 * Esta interface é um serviço  (Web Service) destinado a comunicação 
 * entre servidores e não deve ser acessado de forma interativa por 
 * usuários finais.
 * <P>
 * Este serviço permite a aplicações remotas consumir faixas de uma 
 * determinada sequencia para ser utilizado em ambientes replicados.
 * <P>
 * Telescope origin: SEQUENCE.UTL_SEQUENCE_RANGE
 * <P>
 * Base entity: SEQUENCE.SEQUENCES
 * <P>
 * @author TELESCOPE - Build task T2 Web Interface Generator
 * <P>
 * @version 0.1
 */
public class UtlSequenceRange extends ServiceModel {
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    public static final String GLOBAL_NAME = "SEQUENCE.UTL_SEQUENCE_RANGE";
    
    @Override
    public String globalName() {
        return GLOBAL_NAME;
    }
    
    {
        setTitle("Serviço de replicação de sequencias");
    }
    
    protected EntSequences base;
    protected EntSequences rec; // NEED_TJW1_COMPATIBILITY
    
    // Service parameters
    private DomUpper pSequence;
    private DomInteger pRange;
    private DomPasswordHash pHash;
    private DomUpper pOrigin;
    
    // Record items
    private DomInteger aCache;
    private DomTextLong aDescription;
    private DomId aId;
    private DomBigInteger aMaxValue;
    private DomBigInteger aNextRangeMaxValue;
    private DomBigInteger aNextRangeMinValue;
    private DomBigInteger aNextValue;
    private DomInteger aRangeSize;
    private DomUpper aSequence;
    
    // Query items
    
    @Override
    public String getBaseSql() {
        return "select BASE.*"
                + " from SEQUENCES BASE";
    }
    
    @Override
    public void initAttributes() {
        
        aCache = new DomInteger();
        aCache.context(ctx).name("CACHE").label("Cache");
        aCache.setDefaultValue("1");
        
        aDescription = new DomTextLong();
        aDescription.context(ctx).name("DESCRIPTION").label("Description");
        
        aId = new DomId();
        aId.context(ctx).name("ID").label("Id");
        
        aMaxValue = new DomBigInteger();
        aMaxValue.context(ctx).name("MAX_VALUE").label("Max value");
        
        aNextRangeMaxValue = new DomBigInteger();
        aNextRangeMaxValue.context(ctx).name("NEXT_RANGE_MAX_VALUE").label("Next range max value");
        
        aNextRangeMinValue = new DomBigInteger();
        aNextRangeMinValue.context(ctx).name("NEXT_RANGE_MIN_VALUE").label("Next range min value");
        
        aNextValue = new DomBigInteger();
        aNextValue.context(ctx).name("NEXT_VALUE").label("Next value");
        aNextValue.setDefaultValue("1");
        
        aRangeSize = new DomInteger();
        aRangeSize.context(ctx).name("RANGE_SIZE").label("Range size");
        
        aSequence = new DomUpper();
        aSequence.context(ctx).name("SEQUENCE").label("Sequence");
        
    }
    
    @Override
    public void initParameters() {
        pSequence = new DomUpper(ctx, "SEQUENCE", "Sequence name");
        pSequence.setRequired(true);
        pSequence.setValue(ctx.getParameter("P_SEQUENCE"));
        pSequence.setUnbound(true);
        pRange = new DomInteger(ctx, "RANGE", "Range size");
        pRange.setRequired(true);
        pRange.setValue(ctx.getParameter("P_RANGE"));
        pRange.setUnbound(true);
        pHash = new DomPasswordHash(ctx, "HASH", "Hash");
        pHash.setValue(ctx.getParameter("P_HASH"));
        pHash.setUnbound(true);
        pOrigin = new DomUpper(ctx, "ORIGIN", "Origin");
        pOrigin.setValue(ctx.getParameter("P_ORIGIN"));
        pOrigin.setUnbound(true);
    }
    
    @Override
    public List<Field> getParameters() {
        if (allParameters == null) {
            allParameters = new ArrayList<Field>();
            allParameters.add(pSequence);
            allParameters.add(pRange);
            allParameters.add(pHash);
            allParameters.add(pOrigin);
        }
        return allParameters;
    }
    
    @Override
    public String getQueryPkColumn() {
        return "BASE.ID";
    }
    
    @Override
    public void setId(String value) {
        this.aId.setValue(value);
    }
    
    @Override
    public EntSequences getRecord() {
        if (base == null) {
            base = new EntSequences(ctx);
            rec = base;
        }
        return this.base;
    }
    
    @Override
    public String getDefaultOrderBy() {
        return "";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="GET_RANGE">
    public class FGetRange extends CustomActionFeature {
        
        @Override
        public void initForm() {
        }
        
        @Override
        public int getAccessPolicy() {
            return AccessPolicy.PUBLIC;
        }
        
        @Override
        public void execute() {
            try {
                getRange();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("GET_RANGE");
            setTitle("Get range");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="initFeatures">
    
    @Override
    protected void initFeatures() {
        addFeature(new FGetRange());
        super.initFeatures();
    }
    
    @Override
    public String getDefaultFeature() {
        return "GET_RANGE";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">
    
    public Integer getCache() {
        return aCache.getValue();
    }
    
    public void setCache(Integer value) {
        this.aCache.setValue(value);
    }
    
    public String getDescription() {
        return aDescription.getValue();
    }
    
    public void setDescription(String value) {
        this.aDescription.setValue(value);
    }
    
    @Override
    public Long getId() {
        return aId.getValue();
    }
    
    public void setId(Long value) {
        this.aId.setValue(value);
    }
    
    public Long getMaxValue() {
        return aMaxValue.getValue();
    }
    
    public void setMaxValue(Long value) {
        this.aMaxValue.setValue(value);
    }
    
    public Long getNextRangeMaxValue() {
        return aNextRangeMaxValue.getValue();
    }
    
    public void setNextRangeMaxValue(Long value) {
        this.aNextRangeMaxValue.setValue(value);
    }
    
    public Long getNextRangeMinValue() {
        return aNextRangeMinValue.getValue();
    }
    
    public void setNextRangeMinValue(Long value) {
        this.aNextRangeMinValue.setValue(value);
    }
    
    public Long getNextValue() {
        return aNextValue.getValue();
    }
    
    public void setNextValue(Long value) {
        this.aNextValue.setValue(value);
    }
    
    public Integer getRangeSize() {
        return aRangeSize.getValue();
    }
    
    public void setRangeSize(Integer value) {
        this.aRangeSize.setValue(value);
    }
    
    public String getSequence() {
        return aSequence.getValue();
    }
    
    public void setSequence(String value) {
        this.aSequence.setValue(value);
    }
    
    public String getParameterSequence() {
        return pSequence.getValue();
    }
    
    public void setParameterSequence(String value) {
        pSequence.setValue(value);
    }
    
    public Integer getParameterRange() {
        return pRange.getValue();
    }
    
    public void setParameterRange(Integer value) {
        pRange.setValue(value);
    }
    
    public String getParameterHash() {
        return pHash.getValue();
    }
    
    public void setParameterHash(String value) {
        pHash.setValue(value);
    }
    
    public String getParameterOrigin() {
        return pOrigin.getValue();
    }
    
    public void setParameterOrigin(String value) {
        pOrigin.setValue(value);
    }
    // </editor-fold>
    
    /**
     * Get range.
     * <p>
     * Serviço utilizado para consumir um range.
     */
    public void getRange() throws AdsException {
        // <user-code id="831504" parentId="831502" hashcode="5a9c0795" length="821">
        // import br.com.telescope.sequence.SequenceManager;
        // import java.util.UUID;
        setShown(true);
        ctx.setContentType("text/plain");
        String password = ctx.getPreference(globalName("PASSWORD_HASH"), UUID.randomUUID().toString());
        if (!password.equals(pHash.getValue())) {
            ctx.output("Status=ERROR");
            ctx.output("Access denied!");
            return;
        }
        try {
            SequenceManager mgr = ctx.getSequenceManager("DEFAULT");
            if (mgr != null) {
                Long value = mgr.nextVal(pSequence.getValue(), ctx.getConnection(), pRange.getValue());
                ctx.output("Status=OK");
                ctx.output("NEXT_VALUE=" + value);
            } else {
                ctx.output("Status=ERROR");
                ctx.output("Sequence not found!");
            }
        } catch (Exception ex) {
            ctx.output("Status=ERROR");
            ctx.output(ex.toString());
        }
        
        // </user-code>
    }
}
